<?php
/**
 * View class handler for generating csv (comma seperated value) files for excel
 *
 * @see ViewBase
 * @access Ben Rowe
 */
class ViewCSV extends ViewBase 
{
	/**
	 * Execute the view object and render it to csv
	 * 
	 * @access private
	 * @return null
	 */
	function _exec()
	{
		$obj = $this->_render();
		echo $this->_toCSV($obj);
	}

	/**
	 * Convert the provided object into a csv file
	 *
	 * @access private
	 * @param std_object $obj
	 * @return null;
	 */
	function _toCSV($obj)
	{
		// ensure that the provided object has both a header & data property
		// if it doesn't it's not valid
		if(isset($obj->header) && isset($obj->data)) {
			$details = $obj->details;
			// set the http headers
			header('content-type: text/csv');
			// the filename outputted is NAME-YYYY-MM-DD.csv (any spaces in the 
			// name are replaced)
			header('content-disposition: attachment; filename="'.str_replace(' ', '_', $details['name']).'-'.date('Y-m-d').'.csv"');
			$header = $obj->header;
			$cols = count($header); // number of columns
			for($i = 0; $i < $cols; $i++) {
				echo '"'.$this->_csvEscape($header[$i]->name).'"';
				if($i < $cols -1) {
					echo ',';
				}
			}
			echo "\r\n";
			$data = $obj->data;
			foreach($data as $row) {
				for($i = 0; $i < $cols; $i++) {
					echo '"'.$this->_csvEscape($row[$i]).'"';
					if($i < $cols -1) {
						echo ',';
					}
				}
				echo "\r\n";
			}
		} else {
			trigger_error('Invalid CSV object. Must contain header & data property!', E_USER_ERROR);
		}
	}
	
	/**
	 * Escape a value so it's save to be put into a csv file
	 *
	 * @param string $string
	 * @return string
	 */
	function _csvEscape($string)
	{
		return str_replace('"', '""', $string);
	}
}

?>